import os

from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from alipay import AliPay

# Create your views here.
from django.views import View

from meiduo_mall.utils.views import LoginRequiredJSONMixin
from orders.models import OrderInfo
from payment.models import Payment


class PaymentView(LoginRequiredJSONMixin, View):
    def get(self,request,order_id):
        user = request.user
        try:
            order = OrderInfo.objects.get(pk=order_id,user=user,status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return JsonResponse({
                'code': 400,
                'errmsg': '订单信息错误'
            })

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,    # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),"keys/alipay_public_key.pem"),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝链接
        order_str = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject=f"美多商城{order_id}",
            return_url=settings.ALIPAY_RETURN_URL
        )
        # 响应登录
        alipay_url = settings.ALIPAY_URL + "?" + order_str
        return JsonResponse({
            'code':0,
            'errmsg': 'ok',
            'alipay_url':alipay_url
        })

class PaymentStatusView(LoginRequiredJSONMixin,View):
    def put(self,request):
        # 前端传入的参数
        query_dict = request.GET
        data = query_dict.dict()
        print(data)
        sign = data.pop('sign')
        trade_id = data.get('trade_no') # 支付宝订单id
        order_id = data.get('out_trade_no') # 自己订单i
        if not all([sign,trade_id,order_id]):
            return JsonResponse({
                'code':400,
                'errmsg': '没有参数'
            })
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG
        )
        result = alipay.verify(data, sign)
        if not result:
            return JsonResponse({
                'code': 400,
                'errmsg': '没钱玩你ma'
            })
        # out_trade_no
        # trade_no
        try:
            order = OrderInfo.objects.get(pk=order_id)
            order.status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
            order.save()
        except OrderInfo.DoesNotExist:
            return JsonResponse({
                'code':400,
                'errmsg': '获取不到参数'
            })
        try:
            Payment.objects.create(
                order=order,
                trade_id=trade_id,
            )
        except Exception as e:
            print("错误信息：",e)
            return JsonResponse({
                'code':400,
                'errmsg': '插入数据错误'
            })
        return JsonResponse({
            'code':0,
            'errmsg': 'ok',
            'trade_id':trade_id
        })



